package com.pshcp.patient.task.job;

import com.external.pay.PayService;
import com.external.pay.domain.RefundDTO;
import com.external.pay.domain.RefundResDTO;
import com.pshcp.common.enums.PayBusinessEnum;
import com.pshcp.common.enums.RegPayStatusEnum;
import com.pshcp.domain.model.OrderReg;
import com.pshcp.manager.messagenotification.MessageNotificationManager;
import com.pshcp.patient.business.OrderRegBusiness;
import com.pshcp.patient.tool.OrderRegTools;
import com.pshcp.service.OrderRegService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 退款任务，调用三方支付退费
 */
@Slf4j
@Component
public class RegOrderRefundPayFeeJob extends QuartzJobBean {

    @Autowired
    private OrderRegService orderRegService;

    @Autowired
    private OrderRegBusiness orderRegBusiness;

    @Autowired
    private PayService payService;

    @Autowired
    private MessageNotificationManager messageNotificationManager;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("start RegOrderRefundPayFeeJob");
        List<OrderReg> orderRegs = orderRegService.refundPayFeeList();
        if(CollectionUtils.isEmpty(orderRegs)){
            log.info("RegOrderRefundPayFeeJob is null. ignore task.");
            return;
        }
        orderRegs.forEach(o -> {
            RefundDTO refundDTO = new RefundDTO();
            refundDTO.setOrderId(o.getId());
            refundDTO.setRefundOrderId(o.getId());
            refundDTO.setAmount(o.getCost());
            refundDTO.setPayBusiness(PayBusinessEnum.REG_PAY.getCode());
            try {
                RefundResDTO resDTO = payService.refund(refundDTO);
                if(resDTO.getPayStatus() != null && resDTO.getPayStatus().intValue() == 0){
                    o.setPayStatus(RegPayStatusEnum.REFUND_OK.getCode());
                }
                if(resDTO.getPayStatus() != null && resDTO.getPayStatus().intValue() == 1){
                    o.setPayStatus(RegPayStatusEnum.REFUND_FAIL.getCode());
                }
                if(resDTO.getPayStatus() != null && resDTO.getPayStatus().intValue() == 2){
                    o.setPayStatus(RegPayStatusEnum.REFUND_ING.getCode());
                }
                orderRegService.update(o);
                if(!RegPayStatusEnum.REFUND_ING.getCode().equals(o.getPayStatus())){
                    messageNotificationManager.sendMessageNotification(OrderRegTools.buildRefundPayFeeMessage(o));
                }
            } catch (Exception e) {
                log.error("RegOrderRefundPayFeeJob fail", e);
            }
        });
    }

}
